﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

using XEvent.Events.Base;
using XEvent.Interface;

namespace XEvent.Instance
{
    public class ControlManagerAgent : IControlManager
    {
        private readonly List<UserControl> _controlList = new List<UserControl>();
        protected ICollection<UserControl> ControlList => _controlList;

        private readonly IDictionary<string, ContentControl> _contentList = new Dictionary<string, ContentControl>();
        protected IDictionary<string, ContentControl> ContentList => _contentList;



        public static void SetRegionManager(ContentControl control, string regionName, IControlManager manager)
        {
            manager.AddToRegion(regionName, control);
        }


        public void Regist<T>() where T : UserControl, new()
        {
            lock (ControlList)
            {
                foreach (var item in ControlList)
                {
                    Type itemType = item.GetType();
                    if (itemType.Equals(typeof(T)))
                    {
                        return;
                    }
                }
                var obj = new T();
                ControlList.Add(obj);
            }
        }

        public void RequestNavigate(string regionName, string target)
        {
            ContentControl contentControl = null;
            UserControl userControl = null;
            lock (ContentList)
            {
                if (ContentList.ContainsKey(regionName))
                {
                    contentControl = ContentList[regionName];
                }
            }
            lock (ControlList)
            {
                foreach (var item in ControlList)
                {
                    Type itemType = item.GetType();
                    if (itemType.Name.Equals(target))
                    {
                        userControl = item;
                        break;
                    }
                }
            }

            if (contentControl != null && userControl != null)
            {
                contentControl.Content = userControl;
            }
        }

        public void AddToRegion(string regionName, ContentControl content)
        {
            lock (ContentList)
            {
                if (!ContentList.ContainsKey(regionName))
                {
                    ContentList.Add(regionName, content);
                }
            }
        }
    }
}
